package com.subfg.api.rabbitmq.consumer;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.rabbitmq.client.Channel;
import com.subfg.api.dao.zlog.ZlogRequestDao;
import com.subfg.api.rabbitmq.constant.QueueApi;
import com.subfg.api.rabbitmq.constant.RoutingKeyApi;
import com.subfg.common.dao.ZlogMQDao;
import com.subfg.common.entity.common.BatchRecordModel;
import com.subfg.common.rabbitmq.constant.ExchangeApi;
import com.subfg.common.rabbitmq.constant.QueueContentModel;
import com.subfg.common.rabbitmq.produer.MQSender;
import com.subfg.common.util.common.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SystemLoggerReceiver {
    private Logger log = LoggerFactory.getLogger(SystemLoggerReceiver.class);

    @Autowired
     private ZlogRequestDao zlogRequestDao;
    @Autowired
    private MQSender mqSender;
    @Autowired
    private ZlogMQDao zlogMQDao;


    @RabbitListener(queues = QueueApi.QUEUE_LOGGER)
    @DS("master")
    public void channelLogger(Message message, QueueContentModel<BatchRecordModel> queueModel, Channel channel) throws IOException {
        log.info("正在进行日志消费!!! 队列id==>>>{}, 消息主题为==>>{} 已消费了==>>{}次", queueModel.getId(), queueModel.getSubject(), queueModel.getCount());
        Long currentTime = TimeUtil.getCurrentTime();
        try {
            if (queueModel.getStatus() == 0) {
                zlogRequestDao.insertUserRequestInfo(queueModel.getData());
                queueModel.setStatus(1);
                queueModel.setSuccessDate(currentTime);
            }
        } catch (Throwable e) {
            log.error("写入日志失败!!!" + e);
            log.error("日志记录失败!!! 队列id==>>>{}, 消息主题为==>>{}", queueModel.getId(), queueModel.getSubject());
            queueModel.setStatus(0);
            Integer count = queueModel.getCount();
            queueModel.setCount(count + 1);
            // 失败!! 少于三次则进行重发
            if (count < 3) {
                log.info("失败消息正在进行重发!!!");
                mqSender.sendMQMessage(ExchangeApi.EXCHANGE_COMMON, RoutingKeyApi.SYSTEM_LOGGER, queueModel);
            }
        } finally {
            queueModel.setLastDate(currentTime);
            try {
                zlogMQDao.updateUserRequestInfo(new BatchRecordModel<QueueContentModel>(queueModel));
            } catch (Exception e) {
                log.error("队列状态修改失败! 严重错误!!!! 可能会导致消息堆积 或 丢失"+e);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
